Ext.define('appmod.controller.knowledge.category.Startup', {
    extend: 'Ext.app.Controller',
    
   	stores:[
		'knowledge.category.Tree',
		'knowledge.category.UserPermList',
		'knowledge.category.DirectUserPermList',
		'knowledge.category.UserGroupPermList'
   	],   

    views: [
		'knowledge.category.TreeDashboard',
		'knowledge.category.Form',
		'knowledge.category.UserAssignForm',
		'knowledge.category.UserPermAssignForm',
		'knowledge.category.UserGroupPermAssignForm'
    ],
	
    refs: [
		{ref: 'knowledgeCateTreeDashboard', selector: 'knowledge-category-treedashboard'},
		{ref:'knowledgeCateTreeGrid' ,selector:'knowledge-category-treedashboard knowledge-tree-grid' }
    ],	

    init: function() {
		var me = this;

    	me.control({

			'knowledge-category-treedashboard button[action=reflashCategory]' : {
				click: {
					fn:me.reflashCategory,
					scope:me
				}
			},			
			'knowledge-category-treedashboard button[action=addCategory]': {
				click:{
					fn:me.showCategoryAddingForm,
					scope:me
				}
			},
			'knowledge-category-treedashboard button[action=saveCategoryUpdate]': {
				click:{
					fn:me.saveCategoryUpdate,
					scope:me
				}
			},
			'knowledge-category-treedashboard button[action=deleteCategory]': {
				click:{
					fn:me.showDeleteCategoryDialog,
					scope:me
				}
			},
			'knowledge-category-treedashboard menuitem[action=assignUser]': {
				click:{
					fn:me.showAssignUserForm,
					scope:me
				}
			},
			'knowledge-category-treedashboard button[action=assignPermissionToUser]': {
				click:{
					fn:me.showDirectPermissionAssignUserForm,
					scope:me
				}
			},
			'knowledge-category-treedashboard button[action=assignPermissionToUserGroup]': {
				click:{
					fn:me.showDirectPermissionAssignUserGroupForm,
					scope:me
				}
			}																				
    	});
    },

	
	/**
	 * load main compont in this controller to framework container
	 */
	loadInitComp : function() {
		var me = this;
		// --- defined store ---
		var treeCategory = me.getKnowledgeCategoryTreeStore();
		
		var stores = {
			'category' : treeCategory
		};
				
		var mainPanel = Ext.create('appmod.view.knowledge.category.TreeDashboard' , {
			region : 'center',
			border:false,
			stores : stores,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	

	// --- use this app lication
	onLaunch:function(app) {
		var me = this;


	},

	resetCategoryForm:function(btn, event, eOpts) { 
		var upWin = eOpts.window;                   
		                                            
		var formPanel = upWin.down('knowledge-category-form'); 
                                                    
		var form = formPanel.getForm();             
		form.reset();		                        
	},                                              

	reflashCategory:function(btn, event, eOpts) {
		var me = this;
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var dsCateTree = knowledgeCateTreeGrid.getStore();
		dsCateTree.reload();
	},
	
	showCategoryAddingForm:function() {
		var me = this;
		// --- get the parent id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();



		// --- define category store ---
		var dsCategoryTree = me.getKnowledgeCategoryTreeStore();
	
		var fieldStores = {
			'dsParentCategory' : dsCategoryTree
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '信息分类',
				closable : true,
				width : 250,
				height : 160,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.category.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addCategory'
        				},{
            				text: '清 空 ',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-category-form");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffParentId = form.down('treepicker[name=parentId]');
			ffParentId.setValue(recs[0].getId());
		}
		
		var saveBtn = win.down('button[action="addCategory"]');
		saveBtn.on("click",me.saveAddCategory , me , {
			window : win
		});

		var resetBtn = win.down('button[action="reset"]');
		resetBtn.on("click",me.resetCategoryForm , me , {            
			window : win                                             
		});                                                          

		if ( !win.isVisible() ) {
			win.show();
		}		
	},
	
	saveAddCategory:function(btn, event, eOpts) { 
		var me = this;

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('knowledge-category-form');

		var form = formPanel.getForm();
		
		// --- get submit form value ---
		var submitValues = form.getValues();
		// --- get list panel and reflash ---
		var treeGrid = me.getKnowledgeCateTreeGrid();

		form.submit({
			url:'../../data/resource/knowledge/category/submit_addcate.json',
			success:function(form , action) {
				 Ext.Msg.alert('成功', action.result.msg);
				 if (upWin.isVisible()) {
				 	upWin.close();
				 }
				 
				 var store = treeGrid.getStore();
				 if (store) {
				 	store.reload();
				 }
				 
			},
			failure: function(from, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	},
	
	saveCategoryUpdate:function() {
		var me = this;
		
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();

		var store = knowledgeCateTreeGrid.getStore();

		//var store = me.getResourcesModuleAllFunsStore();

		var proxy =store.getProxy();
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '信息分类更新成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});		
	},
	
	                                                                        
	submitEditProduct:function(btn, event, eOpts) {                        
		var me = this;                                                      
                                                                            
		var upWin = eOpts.window;                                           
		                                                                    
		var formPanel = upWin.down('product-form');                         
                                                                            
		var form = formPanel.getForm();                                     
		                                                                    
		// --- get list panel and reflash ---                               
		var prodList = me.getProductList();                         
                                                                            
		form.submit({                                                       
			url:'../../data/resource/product/submit_updateproduct.json',    
			success:function(form , action) {                               
				 Ext.Msg.alert('成功', action.result.msg);                    
				 if (upWin.isVisible()) {                                   
				 	upWin.close();                                          
				 }                                                          
				                                                            
				 var store = prodList.getStore();                       
				 if (store) {                                               
				 	store.load();                                           
				 }                                                          
				                                                            
			},                                                              
			failure: function(from, action){                                
				switch (action.failureType) {                               
					case Ext.form.action.Action.CLIENT_INVALID:             
						Ext.Msg.alert('失败', '表单里包含错误的信息');                  
						break;                                              
					case Ext.form.action.Action.CONNECT_FAILURE:            
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');             
						break;                                              
					case Ext.form.action.Action.SERVER_INVALID:             
						Ext.Msg.alert('失败', action.result.msg);             
				}                                                           
			}                                                               
		});                                                                 
	} ,
	
	showDeleteCategoryDialog:function(item, eventObj, eOpts) {
		var me = this;

		// --- get contact person id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();		
		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择删除子节点',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} 		

		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < recs.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			if (!recs[i].get('leaf')) {
				// --- is folder node ---
				Ext.MessageBox.show({
	        		title: "提示",
	        		msg: '不能选择父级节点 "'+recs[i].get('text')+'".',
	        		buttons: Ext.MessageBox.OK,
	        		icon: Ext.MessageBox.WARNING
	       		});
				return ;				

			}
			
			removeRecs += recs[i].get('text');
		}
		Ext.MessageBox.confirm('确认', '确定要删除知识分类: "'+removeRecs+'"?',me.confirmDelCategories , me);
	},
	
	confirmDelCategories:function(confirm) {
		var me = this;
		
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();
		
		if (confirm == "no") {
			return;
		}


		var jsonObj = [];
		for (var i = 0 ; i < recs.length ; i++) {
			jsonObj.push(recs[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/knowledge/category/submit_deletecategories.json',
				method:'post',
				jsonData:jsonObj,
				success: function(response, opts) {

					// --- update load ---
					knowledgeCateTreeGrid.getStore().reload();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
					alert("error alert for deleting provider contact person!");
		
				}
			});

			
		} catch (e) {
			Ext.log({
				msg:'error : ' + e
			})
		}			
	},                                                                     
	                                                                        	
	showAssignUserForm:function() {

		var me = this;
		// --- get the parent id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();



		// --- define category store ---
		
		var dsKnowCateUserPerm = me.getKnowledgeCategoryUserPermListStore();
		
	
		var dsCategoryTree = me.getKnowledgeCategoryTreeStore();
	
		var fieldStores = {
			'dsParentCategory' : dsCategoryTree,
			'dsKnowCateUserPerm' : dsKnowCateUserPerm
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '使用指定',
				closable : true,
				width : 400,
				height : 370,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.category.userassignform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '关 闭',
							action:'closeWin'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-category-userassignform");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffCategoryId = form.down('hiddenfield[name=categoryId]');
			var ffCategoryName =  form.down('displayfield[name=categoryName]');
			
			ffCategoryId.setValue(recs[0].getId());
			ffCategoryName.setValue(recs[0].get('text'));
			
			// --- get bind store in panel ---
			var userPermList = form.down('knowledge-category-userpermlist');
			var dsUserPermList = userPermList.getStore();
			var dsProxy = dsUserPermList.getProxy();
			dsProxy.extraParams = {
				categoryId:recs[0].getId()
			}
			dsUserPermList.load();


		}
		


		var closeBtn = win.down('button[action="closeWin"]');
		closeBtn.on("click",function() {
			if (win) {
				win.close();
			}
		} , me , {            
			window : win                                             
		});                                                          

		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	
	showDirectPermissionAssignUserForm:function() {

		var me = this;
		// --- get the parent id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();



		// --- define category store ---
		var dsDirectPerm = me.getKnowledgeCategoryDirectUserPermListStore();	
		
		var fieldStores = {
			'dsDirectPerm' : dsDirectPerm
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '权限指定',
				closable : true,
				width : 800,
				height : 400,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.category.userpermassignform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '关 闭',
							action:'closeWin'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-category-userpermassignform");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffCategoryId = form.down('hiddenfield[name=categoryId]');
			var ffCategoryName =  form.down('displayfield[name=categoryName]');
			
			ffCategoryId.setValue(recs[0].getId());
			ffCategoryName.setValue(recs[0].get('text'));
			
			// --- get bind store in panel ---
			var userPermList = form.down('knowledge-category-directuserpermlist');
			var dsUserPermList = userPermList.getStore();
			var dsProxy = dsUserPermList.getProxy();
			dsProxy.extraParams = {
				categoryId:recs[0].getId()
			}
			dsUserPermList.load();
		}
		
		var saveBtn = win.down('button[action="updateAuth"]');
		saveBtn.on("click" ,me.updateNewUserPerm,  me , {            
			window : win                                             
		});
		
		var closeBtn = win.down('button[action="closeWin"]');
		closeBtn.on("click",function() {
			if (win) {
				win.close();
			}
		} , me , {            
			window : win                                             
		});
		
		// --- defined app event ---
		var adminColCheck = win.down('knowledge-category-directuserpermlist checkcolumn[dataIndex=isAdmin]');
		adminColCheck.on('change' , me.updateAllCheckboxField , me , {
			window : win
		});


		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	updateAllCheckboxField:function(thisself, newValue, oldValue, eOpts) {
		console.log(newValue + " , " + oldValue);
	},
	
	
	updateNewUserPerm:function(item, eventObj, eOpts) {
		var me = this;
		
		var win = eOpts.window;
		var gridList = win.down("knowledge-category-directuserpermlist");

		var store = gridList.getStore();

		var proxy =store.getProxy();
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '用户权限定义成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});			
	},
	
	showDirectPermissionAssignUserGroupForm :function() {
		var me = this;
		// --- get the parent id ---
		var knowledgeCateTreeGrid = me.getKnowledgeCateTreeGrid();
		var selMod = knowledgeCateTreeGrid.getSelectionModel();
		var recs = selMod.getSelection();


		// --- define category store ---
		var dsPerm = me.getKnowledgeCategoryUserGroupPermListStore();	
		
		var fieldStores = {
			'dsPerm' : dsPerm
		};

		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '用户组设定',
				closable : true,
				width : 800,
				height : 400,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'knowledge.category.usergrouppermassignform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '关 闭',
							action:'closeWin'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("knowledge-category-usergrouppermassignform");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffCategoryId = form.down('hiddenfield[name=categoryId]');
			var ffCategoryName =  form.down('displayfield[name=categoryName]');
			
			ffCategoryId.setValue(recs[0].getId());
			ffCategoryName.setValue(recs[0].get('text'));
			
			// --- get bind store in panel ---
			var usergroupPermList = form.down('knowledge-category-usergrouppermlist');
			var dsUserGroupPermList = usergroupPermList.getStore();
			var dsProxy = dsUserGroupPermList.getProxy();
			dsProxy.extraParams = {
				categoryId:recs[0].getId()
			}
			dsUserGroupPermList.load();
		}
		
		var saveBtn = win.down('button[action="updateUserGroupAuth"]');
		saveBtn.on("click" ,me.updateUserGroupPerm,  me , {            
			window : win                                             
		});
		
		var closeBtn = win.down('button[action="closeWin"]');
		closeBtn.on("click",function() {
			if (win) {
				win.close();
			}
		} , me , {            
			window : win                                             
		});
		
		// --- defined app event ---
		var adminColCheck = win.down('knowledge-category-usergrouppermlist checkcolumn[dataIndex=isAdmin]');
		adminColCheck.on('change' , me.updateAllCheckboxField , me , {
			window : win
		});


		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	updateUserGroupPerm:function(item, eventObj, eOpts) {
		var me = this;
		
		var win = eOpts.window;
		var gridList = win.down("knowledge-category-usergrouppermlist");

		var store = gridList.getStore();

		var proxy =store.getProxy();
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '用户组权限定义成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});			
	}
		
		
});